package com.woniuxy.rabbitmq79.direct;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.Random;

/**
 * @Author zhangyong
 * @Date 2021/8/11 0011下午 2:56
 */
public class Productor {
    public static void main(String[] args) throws Exception {
        //1.创建连接工厂：创建连接
        ConnectionFactory factory = new ConnectionFactory();

        //2.设置连接参数
        factory.setHost("localhost");   //mq的ip
        factory.setUsername("guest");   //账号
        factory.setPassword("guest");   //密码
        factory.setVirtualHost("/");    //设置虚拟主机 不设置默认/

        //3.创建连接
        Connection connection = factory.newConnection();     //IO异常

        //4.创建通道
        Channel channel = connection.createChannel();

        //创建交换机
        channel.exchangeDeclare("direct_exchange", "direct");

        String[] routes = {"chengdu", "beijing"};
        Random random = new Random();

        //发送消息
        for (int i = 0; i < 10; i++) {
            String message = "direct" + i;
            String route = routes[random.nextInt(2)];
            channel.basicPublish("direct_exchange", route, null, message.getBytes());
        }
        //
        channel.close();
        connection.close();
    }
}
